﻿//-----------------------------------------------------------------------
// <copyright file="LogEntryRepository.cs" company="FastNET Services">
//     Copyright (c) 2008-2009. All Rights Reserved.
// </copyright>
// <license>
//     GPLv2
// </license>
// <warranty>
//     THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING
//     BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
//     NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
//     DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
//     OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// </warranty>
//-----------------------------------------------------------------------
#region Usings
using System;
using System.Collections.Generic;
using System.Data.EntityClient;
using System.Linq;
using FastNET.CleanAct.Client.ManagerEngineData.Entities;
using FastNET.CleanAct.Common.Repository;
using FastNET.CleanAct.Common.Repository.Interfaces.DataInterfaces.General;
using FastNET.CleanAct.Common.Repository.Interfaces.Repositories.General;


#endregion

namespace FastNET.CleanAct.Client.ManagerEngineData.Repositories
{
    /// <summary>
    /// General repository for managing LogEntries
    /// </summary>
    internal class LogEntryRepository
        : ILogEntryRepository
    {
        #region CTor/DTor

        /// <summary>
        /// Initializes a new instance of the LogEntryRepository class
        /// </summary>
        /// <param name="connection">Reference to the common EntityConnection for the repository</param>
        internal LogEntryRepository(EntityConnection connection)
        {
            Connection = connection;
        }

        #endregion

        #region Properties

        /// <summary>
        /// Gets a reference to the common EntityConnection for the repository
        /// </summary>
        protected EntityConnection Connection { get; private set; }

        #endregion

        #region IRepository<ILogEntryData> Members

        /// <summary>
        /// Retrieves all instances of ILogEntryData from the repository
        /// </summary>
        /// <returns>IEnumerable of the requested IData</returns>
        public IList<ILogEntryData> Retrieve()
        {
            List<ILogEntryData> returnValues = new List<ILogEntryData>();

            using (ManagerDataEntities dataSource = new ManagerDataEntities(Connection))
            {
                IEnumerable<Log> query = from item in dataSource.Logs select item;

                foreach (Log item in query)
                {
                    returnValues.Add(item);
                    dataSource.Detach(item);
                }
            }

            return returnValues;
        }

        /// <summary>
        /// Retrieves the requested ILogEntryData by an Identity
        /// </summary>
        /// <param name="ID">Identity to retrieve the data by</param>
        /// <returns>IData instance or null if one was not found</returns>
        /// <exception cref="InvalidCastException">Thrown if the identity is of the wrong type for this datasource</exception>
        public ILogEntryData Retrieve(Identity ID)
        {
            if (!ID.CanFitInGuid())
            {
                throw new InvalidCastException(string.Format("Identity for this type of repository requires it to be of Guid Type. Currently is {0}.", ID.UnderlyingType()));
            }

            // This has to be done here because LINQ does not support the inline case
            Guid searchID = ID;

            using (ManagerDataEntities dataSource = new ManagerDataEntities(Connection))
            {
                Log foundItem = (from
                                                item
                                                in
                                     dataSource.Logs
                                 where
                                     item.LogID == searchID
                                 select
                                     item).FirstOrDefault();

                if (foundItem != null)
                {
                    dataSource.Detach(foundItem);
                }

                return foundItem;
            }
        }

        /// <summary>
        /// Deletes the requested ILogEntryData
        /// </summary>
        /// <param name="Data">ILogEntryData to delete from the repository</param>
        /// <exception cref="ArgumentNullException">Thrown if data is null</exception>
        /// <exception cref="InvalidCastException">Thrown if the data is of the wrong type for this datasource</exception>
        /// <exception cref="InvalidOperationException">Thrown if the ILogEntryData is new or already deleted</exception>
        public void Delete(ILogEntryData Data)
        {
            if (Data == null)
            {
                throw new ArgumentNullException("Data", "Must have a valid Data to delete");
            }

            if (!(Data is Log))
            {
                throw new InvalidCastException("Data is not of type LogEntry. Cannot delete this object through this repository");
            }

            if (Data.IsNew)
            {
                throw new InvalidOperationException("Data cannot be new before deleting. There is nothing to delete.");
            }

            if (Data.IsDeleted)
            {
                throw new InvalidOperationException("Data already deleted.");
            }

            using (ManagerDataEntities dataSource = new ManagerDataEntities(Connection))
            {
                dataSource.Attach((Log)Data);
                dataSource.DeleteObject(Data);
                dataSource.SaveChanges();
            }
        }

        /// <summary>
        /// Saves the requested ILogEntryData
        /// </summary>
        /// <param name="Data">ILogEntryData to save to the repository</param>
        /// <exception cref="ArgumentNullException">Thrown if data is null</exception>
        /// <exception cref="InvalidCastException">Thrown if the data is of the wrong type for this datasource</exception>
        public void Save(ILogEntryData Data)
        {
            if (Data == null)
            {
                throw new ArgumentNullException("Data", "Must have a valid Data to delete");
            }

            if (!(Data is Log))
            {
                throw new InvalidCastException("Data is not of type LogEntry. Cannot save this object through this repository");
            }

            if (!Data.IsDirty)
            {
                return;
            }

            using (ManagerDataEntities dataSource = new ManagerDataEntities(Connection))
            {
                if (Data.IsNew)
                {
                    dataSource.AddToLogs((Log)Data);
                    dataSource.SaveChanges();
                    dataSource.Detach(Data);
                }
                else
                {
                    dataSource.ApplyPropertyChanges("Logs", Data);
                    dataSource.SaveChanges();
                }
            }
        }

        /// <summary>
        /// Creates a new instance of ILogEntryData
        /// </summary>
        /// <returns>New Instance of ILogEntryData</returns>
        public ILogEntryData Create()
        {
            return new Log();
        }

        #endregion
    }
}